package com.tebiecloud.goods.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tebiecloud.act.client.model.entity.Act;
import com.tebiecloud.common.constants.ResultEnum;
import com.tebiecloud.common.security.SecurityHelper;
import com.tebiecloud.common.security.SecurityUserDetails;
import com.tebiecloud.common.utils.RedisUtils;
import com.tebiecloud.common.utils.StringUtils;
import com.tebiecloud.goods.client.constants.GoodsConstants;
import com.tebiecloud.goods.client.model.entity.Goods;
import com.tebiecloud.goods.client.model.entity.GoodsSharePic;
import com.tebiecloud.goods.server.service.GoodsService;
import com.tebiecloud.goods.server.service.GoodsSharePicService;
import com.tebiecloud.common.model.PageParams;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.common.utils.ResultBodyUtils;
import com.tebiecloud.goods.server.service.feign.ActServiceClient;
import com.tebiecloud.goods.server.service.feign.OssServiceClient;
import com.tebiecloud.goods.server.utils.DrawGoodsImage;
import com.tebiecloud.goods.server.utils.QRCodeGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;

import javax.swing.filechooser.FileSystemView;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

/**
 *  前端控制器
 * @author tebie
 * @date 2019-10-17
 */
@Slf4j
@RestController
@RequestMapping("/goodssharepic")
public class GoodsSharePicController {

    @Autowired
    private GoodsSharePicService goodsSharePicService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private ActServiceClient actServiceClient;

    @Autowired
    private OssServiceClient ossServiceClient;

    @Autowired
    private RedisUtils redisUtils;


    /**
     *
     * @param goodsId
     * @return
     */
    @PostMapping("getsharepic")
    public ResultBody getsharepic(
                            @RequestParam(value = "goodsId") long goodsId,
                            @RequestParam(value = "goodsSpecificationId") long goodsSpecificationId,
                            @RequestParam(value = "price") int price,
                            @RequestParam(value = "retailPrice") int retailPrice,
                            @RequestParam(value = "actId",required = false) Long actId,
                            @RequestParam(value = "userId", required = false) Long userId) {
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
//        long userId = securityUserDetails.getUserId();
        //先查询redis
        String key = GoodsConstants.REDIS_GOODS_SHARE_PIC_+goodsSpecificationId;
        if(actId!=null){
            key = key+actId;
        }
        key = key + price + retailPrice;
        if(redisUtils.get(key)!=null){
            return ResultBodyUtils.ok(redisUtils.get(key));
        }
        String url = "https://tebie.gzqqs.com/pic/#/GoodsDetail?sourceUserId="+userId+"&goodsId=" + goodsId;
        if(actId!=null){
            url = url + "&actId=" + actId;
        }
        //查询商品分享图
        String sharePicUrl = "";
        String goodsName = "";
        if(actId!=null){
            ResultBody<Act> actResultBody = actServiceClient.selectActByActId(actId);
            if(actResultBody!=null && actResultBody.getCode() == ResultEnum.OK.getCode()){
                Act act = actResultBody.getData();
                if(act!=null)sharePicUrl = act.getSharePic();
                goodsName = act.getName();
            }
        }else {
            QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
            goodsQueryWrapper.eq("goods_id",goodsId);
            Goods goods = goodsService.getOne(goodsQueryWrapper);
            if(goods!=null)sharePicUrl = goods.getSharePic();
            goodsName = goods.getName();
        }
        if(StringUtils.isEmpty(sharePicUrl))return ResultBodyUtils.failed("获取分享图片错误");
        String qrUrl = "https://gumiho.oss-cn-hangzhou.aliyuncs.com/tebie/20191014/act/qr.png";
        BufferedImage bufferedImage = QRCodeGenerator.createQrCode(url);
        File file = null;
        try {
            file = DrawGoodsImage.drawImage(sharePicUrl,bufferedImage,qrUrl,goodsName,price,retailPrice);
        }catch (IOException e){
            log.info(e.getLocalizedMessage());
        }
        if(file==null)return ResultBodyUtils.failed();
        //分享图片
        String sharePic = "";
        ResultBody resultBody = ossServiceClient.uploadImage("shop",file);
        if(resultBody!=null && resultBody.getCode() == ResultEnum.OK.getCode()){
            sharePic = resultBody.getData().toString();
            log.info(">> minjie 分享图片地址：{}",sharePic);
        }
        if(StringUtils.isEmpty(sharePic))return ResultBodyUtils.failed("上传图片失败");
        //存入数据库
        GoodsSharePic goodsSharePic = new GoodsSharePic();
        goodsSharePic.setActId(actId);
        goodsSharePic.setGoodsId(goodsId);
        goodsSharePic.setGoodsSpecificationId(goodsSpecificationId);
        goodsSharePic.setSharePic(sharePic);
        goodsSharePic.setUserId(userId);
        goodsSharePicService.saveOrUpdate(goodsSharePic);
        //存入redis，过期时间为一周
        redisUtils.set(key,sharePic,24*60*60*7);
        return resultBody;
    }

//    /**
//     * 获取分页数据
//     * @param map
//     * @return
//     */
//    @GetMapping(value = "list")
//    public ResultBody<IPage<GoodsSharePic>> list(@RequestParam(required = false) Map map) {
//        PageParams pageParams = new PageParams(map);
//        GoodsSharePic query = pageParams.mapToObject(GoodsSharePic.class);
//        QueryWrapper<GoodsSharePic> queryWrapper = new QueryWrapper();
//        return ResultBodyUtils.ok(goodsSharePicService.page(new PageParams(map), queryWrapper));
//    }
//
//    /**
//     * 根据ID查找数据
//     * @param id
//     * @return
//     */
//    @GetMapping("get")
//    public ResultBody<GoodsSharePic> get(@RequestParam("id") Long id) {
//        GoodsSharePic entity = goodsSharePicService.getById(id);
//        return ResultBodyUtils.ok(entity);
//    }
//
//    /**
//     * 添加数据
//     * @param userId 用户id,
//     * @param goodsId 商品id,
//     * @param actId 活动id,
//     * @param sharePic 分享图片
//     * @return
//     */
//    @PostMapping("add")
//    public ResultBody add(
//        @RequestParam(value = "userId", required = false) Long userId,
//        @RequestParam(value = "goodsId", required = false) Long goodsId,
//        @RequestParam(value = "actId", required = false) Long actId,
//        @RequestParam(value = "sharePic", required = false) String sharePic
//    ) {
//        GoodsSharePic entity = new GoodsSharePic();
//        entity.setUserId(userId);
//        entity.setGoodsId(goodsId);
//        entity.setActId(actId);
//        entity.setSharePic(sharePic);
//        goodsSharePicService.save(entity);
//        return ResultBodyUtils.ok();
//    }
//
//    /**
//     * 更新数据
//     * @param userId 用户id
//     * @param goodsId 商品id
//     * @param actId 活动id
//     * @param sharePic 分享图片
//     * @return
//     */
//    @PostMapping("update")
//    public ResultBody update(
//            @RequestParam(value = "goodsShareId", required = false) Long goodsShareId,
//            @RequestParam(value = "userId", required = false) Long userId,
//            @RequestParam(value = "goodsId", required = false) Long goodsId,
//            @RequestParam(value = "actId", required = false) Long actId,
//            @RequestParam(value = "sharePic", required = false) String sharePic
//    ) {
//        GoodsSharePic entity = new GoodsSharePic();
//        entity.setGoodsShareId(goodsShareId);
//        entity.setUserId(userId);
//        entity.setGoodsId(goodsId);
//        entity.setActId(actId);
//        entity.setSharePic(sharePic);
//        goodsSharePicService.updateById(entity);
//        return ResultBodyUtils.ok();
//    }
//
//    /**
//     * 删除数据
//     * @param id 单个id
//     * @param ids 多个id用,号隔开
//     * @return
//     */
//    @PostMapping("remove")
//    public ResultBody remove(
//            @RequestParam(value = "id", required = false) Long id,
//            @RequestParam(value = "ids", required = false) String ids
//    ) {
//        if(id != null && id > 0) {
//            goodsSharePicService.removeById(id);
//        }
//        if(ids != null && ids.length() > 0) {
//            goodsSharePicService.removeByIds(Arrays.asList(ids.split(",")));
//        }
//        return ResultBodyUtils.ok();
//    }

}
